package com.gsit.job.flows;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.springframework.beans.factory.annotation.Autowired;

import com.gsit.job.config.Config;
import com.gsit.job.domain.User;
import com.gsit.job.services.PersonFileWriter;
import com.gsit.job.services.PersonService;
import com.gsit.job.services.UrlParser;

public abstract class BaseFlow {
	
	protected WebDriver driver = null;
	
	@Autowired
	protected PersonService personService;
	
	@Autowired
	protected PersonFileWriter fileWriter;
	
	@Autowired
	protected UrlParser parser;
	
	
	public void execute( ){
		System.out.println("FlowService is starting");
		start();
		
	}
	
	protected void start(){
		driver = new FirefoxDriver();
		doLogin();
		sleep(1000);
		try {
			process();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		sleep(2000);
		doLogOff();
		
	}
	
	
	protected void doLogOff() {
		driver.get(Config.LOGOUT_URL);
		WebElement element = driver.findElement(By.linkText("Logout"));
		System.out.println("Log out .....");
		element.click();
		driver.close();
		
	}
	
	protected void doLogin() {
		SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yy 'at' HH:mm:ss");
		System.out.println("Login to your System , time " + dateFormat.format(new Date()));
		driver.get(Config.LOGIN_URL);
		
		//btn-slide
		WebElement element = driver.findElement(By.id("username"));
		User user = Config.createUser();
		
		if (element != null) {
			element.sendKeys(user.getUserName());
		}
		element = driver.findElement(By.id("password"));
		if (element != null) {
			element.sendKeys(user.getPassword());
		}
		element.submit();
		
	}
	
	protected void sleep(long ms) {
		try {
			Thread.sleep(ms);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	

	protected abstract void process()throws Exception;
	

}
